/*
 * Copyright 2015-2016 TakWolf
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dxyxx.utils;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import java.lang.Thread.UncaughtExceptionHandler;

import com.dxyxx.R;
import com.dxyxx.framework.CrashLogActivity;

public final class CrashHandler implements UncaughtExceptionHandler {

	private volatile static CrashHandler singleton;

	private static CrashHandler getInstance(Context context) {
		if (singleton == null) {
			synchronized (CrashHandler.class) {
				if (singleton == null) {
					singleton = new CrashHandler(context);
				}
			}
		}
		return singleton;
	}

	public static void active(Context context) {
		Thread.setDefaultUncaughtExceptionHandler(getInstance(context));
	}

	private Context context;

	private CrashHandler(Context context) {
		this.context = context.getApplicationContext();
	}

	@Override
	public void uncaughtException(Thread thread, final Throwable e) {
		Intent intent = new Intent(context, CrashLogActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Bundle bundle = new Bundle();
		bundle.putSerializable("e", e);
		intent.putExtras(bundle);
		context.startActivity(intent);
		android.os.Process.killProcess(android.os.Process.myPid());
	}

}
